package com.trainoo.mina.demo;

import com.trainoo.mina.codec.MessageCodecFactory;
import com.trainoo.mina.filter.MyLastServerFilter;
import com.trainoo.mina.handler.MyServerHandler;
import com.trainoo.mina.filter.MyFirstServerFilter;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.LineDelimiter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.logging.Level;

/**
 * @Auther: zt
 * @Date: 2020/4/14 14:28
 * @Description:
 */
public class MinaServerDemo {

    private static final Logger LOG = LoggerFactory.getLogger(MinaServerDemo.class);
    private static final int PORT = 22222;

    public static void main(String[] args) {
        IoAcceptor acceptor;
        try {
            // 创建一个非阻塞的server端的Socket
            acceptor = new NioSocketAcceptor();
            // 设置编码过滤器（使用Mina提供的文本换行符编解码器）
            /*acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(
                    new TextLineCodecFactory(
                            Charset.forName("UTF-8"),
                            LineDelimiter.WINDOWS.getValue(),
                            LineDelimiter.WINDOWS.getValue()
                    )
            ));*/

            // 自定义编码解码器
            acceptor.getFilterChain().addLast("myCodec", new ProtocolCodecFilter(
                    new MessageCodecFactory(Charset.forName("UTF-8"))
            ));

            // 添加自定义的过滤器
            acceptor.getFilterChain().addFirst("firstFilter", new MyFirstServerFilter());
            acceptor.getFilterChain().addLast("lastFilter", new MyLastServerFilter());
            acceptor.getFilterChain().addLast("loggerFilter", new LoggingFilter());

            // 设置读取数据的缓冲区大小
            acceptor.getSessionConfig().setReadBufferSize(1024);
            // 设置读写通道无操作进入空闲状态的时间 10ms
            acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
            // 绑定真正的逻辑处理
            acceptor.setHandler(new MyServerHandler());
            // 绑定端口
            acceptor.bind(new InetSocketAddress(PORT));
            LOG.info("Mina服务端启动成功，监听：" + PORT);
        } catch (IOException e) {
            LOG.error("服务端启动出错-----" + e);
        }
    }
}
